//
//  PGContentView.m
//  TapContent
//
//  Created by Pill Gong on 14-4-18.
//  Copyright (c) 2014年 Pill Gong. All rights reserved.
//

#import "PGContentView.h"

@implementation PGContentView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}


- (id)init {
    self = [super initWithFrame:CGRectZero];
    if (self) {
        [self setDefaultValue];
    }
    return self;
}

- (void)setDefaultValue {
    _responseTap = YES;
    self.layer.cornerRadius = 5;
    _highlightColor = [UIColor lightGrayColor];
    _lateralPadding = 2;
    _verticalPadding = 2;
}

- (void)setCornerRadius:(CGFloat)cornerRadius {
    _cornerRadius = cornerRadius;
    self.layer.cornerRadius = _cornerRadius;
}

- (void)setHighlightColor:(UIColor *)highlightColor {
    _highlightColor = highlightColor;
    self.layer.backgroundColor = [highlightColor CGColor];
}

- (void)setSubView:(UIView *)subView {
    _subView = subView;

    if ([subView isKindOfClass:[UILabel class]]) {
        _subView.backgroundColor = [UIColor clearColor];
    }
    
    CGRect rect = _subView.frame;
    rect.origin.x -= _lateralPadding*0.5;
    rect.origin.y -= _verticalPadding*0.5;
    rect.size.width += _lateralPadding;
    rect.size.height += _verticalPadding;
    self.frame = rect;
    
    [_subView.superview addSubview:self];
    [_subView removeFromSuperview];

    CGRect newFrame = _subView.frame;
    newFrame.origin = CGPointMake(_lateralPadding*0.5, _verticalPadding*0.5);
    _subView.frame = newFrame;

    [self addSubview:_subView];
}

- (void)updateBackGroundColor:(BOOL)animated {
    if (animated) {
        self.layer.backgroundColor = [_highlightColor CGColor];
    } else {
        self.layer.backgroundColor = [[UIColor clearColor] CGColor];
    }
}

#pragma mark - Touches

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self updateBackGroundColor:YES];
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
    [self updateBackGroundColor:NO];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    [self updateBackGroundColor:NO];
    if (_responseTap) {
        if (_delegate && [_delegate respondsToSelector:@selector(contentViewTouchUpInside:)]) {
            [_delegate contentViewTouchUpInside:self];
        }
    }
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    [self updateBackGroundColor:NO];
}


@end
